/**
 * @Author:Kindear
 * @Date:2021-09-06
 * @Desc:用户绑定登录云函数
 */
/**
 * @Author:Kindear
 * @Date:2021-09-15
 * @Desc:修改用户绑定形式，数据形式不一致
 */
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const axios = require('axios');
const TimeUtil = require('./timeutil');
const USER = 'edu-cloud-users'
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID;
  let action = event.action;
  switch (action) {
    case 'findById': {
      // 根据ID 查询  
      let docId = event.docId;
      try {
        return await db.collection(USER).doc(docId).get();
      } catch (error) {
        return {
          errCode: -1,
          errMsg: '查询不到用户信息'
        }
      }

      break
    }
    case 'userBind': {
      // 获取用户信息
      let userInfo = event.userInfo;
      // 获取学号 密码相关信息
      // let bindId = event.bindId;
      // let bindPwd = event.bindPwd;
      // 获取返回结果
      let matchRes = await db.collection(USER).where({
        openid
      }).get();
      if (matchRes.data.length == 0) {
        return db.collection(USER).add({
          data: {
            avatarUrl: userInfo.avatarUrl,
            nickName: userInfo.nickName,
            openid: openid,
            _createTime: TimeUtil.TimeCode(),
            _updateTime: TimeUtil.TimeCode()
          }
        })
      } else {
        //更新
        let baseData = matchRes.data[0]
        let docId = baseData._id;
        return db.collection(USER).doc(docId).update({
          data: {
            avatarUrl: userInfo.avatarUrl,
            nickName: userInfo.nickName,
            openid: openid,
            _updateTime: TimeUtil.TimeCode()
          }
        })
      }
      break
    }
  }
}